package spu

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"insighttracking/apps/admin/auth"
	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"
	"insighttracking/common/utils"
	"insighttracking/query/bo"
	"insighttracking/query/model"
	"insighttracking/query/service"
	"net/http"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type BomApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewBomApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *BomApiLogic {
	hostname, _ := os.Hostname()
	return &BomApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *BomApiLogic) CreateApi(req *types.CreateBomReq) (resp string, err error) {
	err = service.SpuService.GetBomByCode(l.ctx, req.Code)
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return "", errors.New("编码已存在")
	}

	account, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return
	}

	orgSpu, err := service.SpuService.GetBySpuIdApi(l.ctx, req.OrgSpuID)
	if err != nil || orgSpu.SpuType != 0 {
		return "", errors.New("原材料必须是基础商品")
	}
	spu, err := service.SpuService.GetBySpuIdApi(l.ctx, req.SpuID)
	if err != nil || spu.SpuType != 1 {
		return "", errors.New("商品必须是加工品")
	}
	entity := model.SpuBomEntity{
		EnterpriseID:      account.EnterpriseId,
		Code:              req.Code,
		Name:              req.Name,
		Describe:          req.Describe,
		OrgSpuID:          req.OrgSpuID,
		SpuID:             req.SpuID,
		OrgSpuName:        req.OrgSpuName,
		SpuName:           req.SpuName,
		ProductionLineIds: "," + req.ProductionLine + ",",
	}
	err = service.SpuService.CreateBom(l.ctx, &entity)
	return
}

func (l *BomApiLogic) ListApi(req *types.BomListReq) (resp *types.BomListResp, err error) {
	resp = &types.BomListResp{}
	list := make([]*types.BomList, 0)
	account, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return
	}
	bomPage := bo.BomPageBoReq{
		Name:           req.Name,
		SpuName:        req.SpuName,
		OrgSpuName:     req.OrgSpuName,
		ProductionLine: req.ProductionLine,
		EnterpriseID:   account.EnterpriseId,
	}
	entities, count, err := service.SpuService.BomList(l.ctx, &bomPage)
	for _, entity := range entities {
		//entity.ProductionLineIds
		item := types.BomList{
			BomType:        1,
			Code:           entity.Code,
			CreatedAt:      utils.TimestampToString(entity.CreatedAt),
			Name:           entity.Name,
			OrgSpuName:     entity.OrgSpuName,
			ProductionLine: entity.ProductionLineIds[1 : len(entity.ProductionLineIds)-1],
			SpuName:        entity.SpuName,
		}
		list = append(list, &item)
	}
	resp.List = list
	resp.PageSize = req.PageSize
	resp.PageNumber = req.PageNumber
	resp.Total = count
	return
}

func (l *BomApiLogic) AssociateApi(req *types.AssociateReq) (resp []bo.AssociateResp, err error) {
	resp = make([]bo.AssociateResp, 0)
	account, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return
	}
	resp, err = service.SpuService.GetListByName(l.ctx, account.EnterpriseId, req.Name, req.SpuType)
	return
}
